package cn.team.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@RestController
public class MainController {

    private final Producer producer;
    @Autowired
    public MainController(Producer producer) {
        this.producer = producer;
    }

    @GetMapping("/getConnection")
    public void netInfo(HttpServletResponse response, @RequestParam("name") String name) throws IOException {
        Map<String, Object> map = new HashMap<>();
        map.put("hello",name);
        map.put("msg","已获得连接");
        ServletOutputStream outputStream = response.getOutputStream();
        new ObjectMapper().writeValue(outputStream,map);
        outputStream.flush();
        outputStream.close();
    }

    @GetMapping("/vc.jpg")
    public void verifyCode(HttpServletResponse response, HttpSession session) {
        String text = producer.createText();
        session.setAttribute("vc", text);
        System.out.println(text);
        BufferedImage bi = producer.createImage(text);
        response.setContentType(MediaType.IMAGE_PNG_VALUE);
        OutputStream os;
        try {
            os = response.getOutputStream();
            ImageIO.write(bi,"jpg",os);
            os.flush();
            os.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
